const superagent = require('superagent');
const fs = require('fs');
const API = require('co-wechat-api');
const path = require('path');
//const sharp = require('sharp');

module.exports = {
	password(password, username, time) {
		var p = think.md5(think.md5(password) + username + time);
		return 'w' + p.substring(0, p.length - 1);
	},

	isPjax() {
		return this.ctx.isPjax();
	},
	isWeixin() {
		let flag = false;
		const agent = this.userAgent.toLowerCase();
		// let key = ["mqqbrowser","micromessenger"];
		const key = ['micromessenger'];
		// 排除 Windows 桌面系统
		if(!(agent.indexOf('windows nt') > -1) || (agent.indexOf('windows nt') > -1 && agent.indexOf('compatible; msie 9.0;') > -1)) {
			// 排除苹果桌面系统
			if(!(agent.indexOf('windows nt') > -1) && !agent.indexOf('macintosh') > -1) {
				for(const item of key) {
					if(agent.indexOf(item) > -1) {
						flag = true;
						break;
					}
				}
			}
		}
		return flag;
	},
	spiderImage(imgUrl, filePath) {
		const deferred = think.defer();
		superagent
			.get(imgUrl)
			.end(function(req, res) {

				fs.writeFileSync(filePath, res.body);
				deferred.resolve(filePath);
			});
		return deferred.promise;
	},
	mathRand() {
		let Num = '';
		for(let i = 0; i < 6; i++) {
			Num += Math.floor(Math.random() * 10);
		}
		return Num;
	},
	async uploadImage(files, module) {

		try {

			let picture = [];
			if(!think.isArray(files)) {
				picture.push(files)
			} else {
				picture = files;
			}
			let date = new Date();
			let yearMonth = date.getFullYear() + "" + (date.getMonth() <= 9 ? '0' + date.getMonth() : date.getMonth());
			if(module) {
				module = module + "/";
			} else {
				module = "";
			}

			let dir = `${think.ROOT_PATH}/www/upload/${module}${yearMonth}`;
			if(!think.isExist(dir)) {
				think.mkdir(dir);
			}

			let pics = [];
			console.log(picture)
			for(let i in picture) {
				if(picture[i].size == 0) {
					continue;
				}

				//图片上传压缩

//				let basename = think.uuid('v1') + ".jpg";
//				let picurl = dir + '/' + basename;
//				const image = sharp(picture[i].path);
//				let metadata = await image.metadata();
//				let width = metadata.width < 600 ? metadata.width : 600;
//				let sharps = image.resize(width).jpeg({
//					quality: 60
//				});
//				await sharps.toFile(picurl);

				//图片上传不压缩
									let imgtype = "";
									switch(picture[i].type) {
				
										case 'image/jpeg':
											imgtype = 'jpg';
											break;
										case 'image/gif':
											imgtype = 'gif';
											break;
										case 'image/png':
											imgtype = 'png';
											break;
										case 'image/jpg':
											imgtype = 'jpg';
											break;
										case 'image/bmp':
											imgtype = 'bmp';
											break;
									}
				
									let basename = think.uuid('v1') + "." + imgtype;
									let picurl = dir + '/' + basename;
									console.log(picture[i].path);
				//
				//					//不可跨目录
				//					//fs.renameSync(picture[i].path, picurl);
				//
									//可跨目录
									let readStream = fs.createReadStream(picture[i].path);
									let writeStream = fs.createWriteStream(picurl);
									readStream.pipe(writeStream);

				let data = {
					url: `/upload/${module}${yearMonth}/${basename}`,
					filename: picture[i].filename,
					type: picture[i].type,
					size: picture[i].size
				}

				pics.push(data);
			}
//			await think.timeout(2000);

			return pics;

		} catch(e) {
			return [];
			console.log(e)
		}

	},
	async wechatApi(wxid) {
		let model = think.model("weixin/config");
		let wxmp = await model.findOne(wxid);
		let api = new API(wxmp.appid, wxmp.appsecret, async function() {
			return JSON.parse(wxmp.access_token);
		}, async function(token) {
			await model.setOne(wxid, {
				access_token: JSON.stringify(token)
			});
		});
		return api;

	},
	appModel(modelName = '', appName = '', config = this.config('model.mysql'), prefix = 'app_') {
		const p = this.ctx.controller.split('/');
		appName = think.isEmpty(appName) ? p[1] : appName;
		return think.appModel(modelName, appName, config, prefix);
	},
	appService(name = '', ser = '', ...args) {
		const p = this.ctx.controller.split('/');
		ser = think.isEmpty(ser) ? p[1] : ser;
		return think.appService(name, ser, ...args);
	},
	appDisplay() {
		// console.log(this.ctx.controller);
		const c = this.ctx.controller.split('/');
		const p = this.ctx.action;
		const pp = path.join(think.ROOT_PATH, 'src', 'controller', 'app', c[1], 'view', c[2]);
		return this.display(`${pp}_${p}`);
	},
	
	

};